﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QAAdmin.Util
{
    class QueryUtil
    {
        public static string GetInClauseQuery(Dictionary<int, string> itemList, String query, String inClauseColumnName)
        {
            bool tempFlag = false;
            int unionCount = 0;
            StringBuilder finalQuery = new StringBuilder();
            StringBuilder subQuery = new StringBuilder();
            string[] queryArr = query.Split(new string[] {"WHERE"}, StringSplitOptions.None);
            if (queryArr.Length > 1)
            {
                subQuery.Append(" AND " + inClauseColumnName + " IN ( ");
            }
            else
            {
                subQuery.Append(" WHERE " + inClauseColumnName + " IN ( ");
            }
            if (itemList.Count > 999)
            {
                for (int i = 0; i < itemList.Count; i += 500)
                {
                    if (tempFlag)
                    {
                        finalQuery.Append(" UNION ");
                        unionCount++;
                    }
                    StringBuilder sbTmp = new StringBuilder(1000);
                    bool appendCom = false;

                    for (int j = i; (j < (i + 500)) && (j < itemList.Count); j++)
                    {
                        if (appendCom)
                        {
                            sbTmp.Append(",");
                        }
                        sbTmp.Append("'").Append(itemList.Values.ToList()[j]).Append("'");
                        appendCom = true;

                    }

                    finalQuery.Append(query + subQuery + sbTmp.ToString() + " ) ");
                    tempFlag = true;
                }

            }
            else
            {
                finalQuery.Append(query);
            }

            return finalQuery.ToString();
        }
    }
}
